<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>致筑网 - 角色管理</title>
    <!-- 引入外部资源 -->
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">

    <!-- 配置Tailwind主题 - 保持与系统一致的风格 -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#0a3d62',      // 工程深蓝（主色调）
                        secondary: '#3c6382',    // 工程浅蓝（辅助色）
                        accent: '#60a3bc',       // 工程亮蓝（强调色）
                        success: '#27ae60',      // 成功色
                        warning: '#f39c12',      // 警告色
                        danger: '#e74c3c',       // 危险色
                        neutral: {
                            100: '#f5f6fa',     // 最浅背景色
                            200: '#dcdde1',     // 边框和分割线
                            300: '#b2bec3',     // 次要文本和图标
                            600: '#636e72',     // 中等重要文本
                            700: '#2d3436',     // 主要文本
                            800: '#1e272e',     // 标题文本
                            900: '#192a56',     // 深色背景
                        }
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                    },
                }
            }
        }
    </script>

    <!-- 自定义工具类 -->
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .sidebar-item-active {
                @apply bg-primary/10 text-primary border-l-4 border-primary;
            }
            .card-shadow {
                @apply shadow-sm hover:shadow-md transition-shadow;
            }
            .btn-action {
                @apply px-3 py-1.5 rounded text-sm font-medium transition-colors;
            }
            .btn-primary {
                @apply btn-action bg-primary text-white hover:bg-primary/90;
            }
            .btn-secondary {
                @apply btn-action bg-white border border-neutral-200 text-neutral-700 hover:bg-neutral-50;
            }
            .btn-danger {
                @apply btn-action bg-danger text-white hover:bg-danger/90;
            }
            .form-input {
                @apply w-full px-3 py-2 border border-neutral-200 rounded-lg focus:ring-2 focus:ring-primary/30 focus:border-primary outline-none transition-all;
            }
            .scrollbar-thin {
                scrollbar-width: thin;
                scrollbar-color: theme('colors.neutral.300') transparent;
            }
            .scrollbar-thin::-webkit-scrollbar {
                width: 5px;
                height: 5px;
            }
            .scrollbar-thin::-webkit-scrollbar-thumb {
                @apply bg-neutral-300 rounded-full hover:bg-neutral-400 transition-colors;
            }
        }
    </style>
</head>
<body class="bg-neutral-100 font-sans text-neutral-700 min-h-screen flex flex-col overflow-hidden">
<!-- 顶部导航栏 -->
<header class="bg-white shadow-sm sticky top-0 z-30">
    <div class="container mx-auto px-4">
        <div class="flex items-center justify-between h-16">
            <!-- 左侧：Logo和名称 -->
            <div class="flex items-center">
                <!-- 移动端菜单按钮 -->
                <button id="mobile-menu-button" class="md:hidden p-2 mr-2 rounded-md text-neutral-600 hover:text-primary hover:bg-neutral-100 transition-colors">
                    <i class="fa fa-bars text-xl"></i>
                </button>

                <!-- 公司Logo和名称 -->
                <div class="flex items-center">
                    <i class="fa fa-cubes text-2xl text-primary mr-3"></i>
                    <span class="text-xl font-bold text-neutral-800">致筑网</span>
                    <span class="hidden md:inline-block ml-2 text-sm text-neutral-600">系统管理后台</span>
                </div>
            </div>

            <!-- 右侧：用户相关功能 -->
            <div class="flex items-center space-x-4">
                <!-- 通知中心 -->
                <div class="relative">
                    <button id="notification-button" class="p-2 rounded-full hover:bg-neutral-100 transition-colors relative">
                        <i class="fa fa-bell text-neutral-600"></i>
                        <!-- 通知数量提示 -->
                        <span class="absolute -top-1 -right-1 w-5 h-5 bg-danger text-white text-xs rounded-full flex items-center justify-center" id="notification-count">2</span>
                    </button>
                </div>

                <!-- 帮助中心 -->
                <button class="p-2 rounded-full hover:bg-neutral-100 transition-colors">
                    <i class="fa fa-question-circle text-neutral-600"></i>
                </button>

                <!-- 用户头像和下拉菜单 -->
                <div class="relative" id="user-menu-container">
                    <button id="user-menu-button" class="flex items-center space-x-2 focus:outline-none">
                        <img src="https://picsum.photos/id/1005/200/200" alt="管理员头像" class="w-8 h-8 rounded-full object-cover border-2 border-white shadow-sm">
                        <span class="hidden md:inline-block text-sm font-medium" id="admin-name">管理员</span>
                        <i class="fa fa-chevron-down text-xs text-neutral-500 hidden md:block"></i>
                    </button>

                    <!-- 用户下拉菜单 - 默认隐藏 -->
                    <div id="user-dropdown-menu" class="hidden absolute right-0 mt-2 w-48 bg-white rounded-lg shadow-lg py-1 z-50 border border-neutral-200">
                        <a href="#" class="block px-4 py-2 text-sm text-neutral-700 hover:bg-neutral-100">
                            <i class="fa fa-user-circle mr-2"></i>个人资料
                        </a>
                        <a href="#" class="block px-4 py-2 text-sm text-neutral-700 hover:bg-neutral-100">
                            <i class="fa fa-cog mr-2"></i>系统设置
                        </a>
                        <div class="border-t border-neutral-200 my-1"></div>
                        <a href="#" id="logout-button" class="block px-4 py-2 text-sm text-danger hover:bg-neutral-100">
                            <i class="fa fa-sign-out mr-2"></i>退出登录
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</header>

<!-- 主要内容区 -->
<main class="flex-1 flex overflow-hidden">
    <!-- 侧边栏导航 - 管理功能菜单 -->
    <aside id="sidebar" class="w-64 bg-white shadow-sm border-r border-neutral-200 flex-shrink-0 hidden md:block overflow-y-auto scrollbar-thin">
        <nav class="p-4">
            <!-- 仪表盘 -->
            <div class="mb-6">
                <h3 class="text-xs font-semibold text-neutral-500 uppercase tracking-wider mb-3">控制台</h3>
                <ul class="space-y-1">
                    <li>
                        <a href="#dashboard" class="flex items-center px-3 py-2 text-sm rounded-md text-neutral-700 hover:bg-neutral-100 transition-colors">
                            <i class="fa fa-dashboard w-6 text-center mr-3"></i>
                            <span>数据概览</span>
                        </a>
                    </li>
                </ul>
            </div>

            <!-- 应用管理 -->
            <div class="mb-6">
                <h3 class="text-xs font-semibold text-neutral-500 uppercase tracking-wider mb-3">应用管理</h3>
                <ul class="space-y-1">
                    <li>
                        <a href="#app-list" class="flex items-center px-3 py-2 text-sm rounded-md text-neutral-700 hover:bg-neutral-100 transition-colors">
                            <i class="fa fa-th-large w-6 text-center mr-3"></i>
                            <span>应用列表</span>
                        </a>
                    </li>
                    <li>
                        <a href="#app-review" class="flex items-center px-3 py-2 text-sm rounded-md text-neutral-700 hover:bg-neutral-100 transition-colors">
                            <i class="fa fa-check-square-o w-6 text-center mr-3"></i>
                            <span>应用审核</span>
                            <span class="ml-auto bg-warning text-white text-xs px-2 py-0.5 rounded-full">5</span>
                        </a>
                    </li>
                    <li>
                        <a href="#app-categories" class="flex items-center px-3 py-2 text-sm rounded-md text-neutral-700 hover:bg-neutral-100 transition-colors">
                            <i class="fa fa-folder w-6 text-center mr-3"></i>
                            <span>分类管理</span>
                        </a>
                    </li>
                </ul>
            </div>

            <!-- 用户管理 -->
            <div class="mb-6">
                <h3 class="text-xs font-semibold text-neutral-500 uppercase tracking-wider mb-3">用户管理</h3>
                <ul class="space-y-1">
                    <li>
                        <a href="#user-list" class="flex items-center px-3 py-2 text-sm rounded-md text-neutral-700 hover:bg-neutral-100 transition-colors">
                            <i class="fa fa-users w-6 text-center mr-3"></i>
                            <span>用户列表</span>
                        </a>
                    </li>
                    <li>
                        <a href="#user-roles" class="sidebar-item-active flex items-center px-3 py-2 text-sm rounded-md">
                            <i class="fa fa-key w-6 text-center mr-3"></i>
                            <span>角色权限</span>
                        </a>
                    </li>
                </ul>
            </div>

            <!-- 系统设置 -->
            <div>
                <h3 class="text-xs font-semibold text-neutral-500 uppercase tracking-wider mb-3">系统设置</h3>
                <ul class="space-y-1">
                    <li>
                        <a href="#system-settings" class="flex items-center px-3 py-2 text-sm rounded-md text-neutral-700 hover:bg-neutral-100 transition-colors">
                            <i class="fa fa-cogs w-6 text-center mr-3"></i>
                            <span>基本设置</span>
                        </a>
                    </li>
                    <li>
                        <a href="#operation-log" class="flex items-center px-3 py-2 text-sm rounded-md text-neutral-700 hover:bg-neutral-100 transition-colors">
                            <i class="fa fa-history w-6 text-center mr-3"></i>
                            <span>操作日志</span>
                        </a>
                    </li>
                </ul>
            </div>
        </nav>
    </aside>

    <!-- 主内容区域 -->
    <div class="flex-1 overflow-y-auto scrollbar-thin p-4 md:p-6 bg-neutral-50">
        <!-- 页面标题和操作区 -->
        <div class="mb-6 flex flex-col md:flex-row md:items-center justify-between">
            <div>
                <h1 class="text-[clamp(1.5rem,3vw,2rem)] font-bold text-neutral-800">角色管理</h1>
                <p class="text-neutral-600 mt-1">
                    <span id="current-date"></span> |
                    <span>总角色数: <span id="total-roles">8</span></span>
                </p>
            </div>
            <div class="mt-4 md:mt-0">
                <button id="add-role-btn" class="btn-primary">
                    <i class="fa fa-plus mr-2"></i>
                    <span>新增角色</span>
                </button>
            </div>
        </div>

        <!-- 搜索和筛选区 -->
        <div class="bg-white rounded-xl p-4 shadow-sm card-shadow mb-6">
            <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                <div>
                    <label for="role-name-search" class="block text-sm font-medium text-neutral-700 mb-1">角色名称</label>
                    <div class="relative">
                        <input type="text" id="role-name-search" class="form-input pl-10" placeholder="请输入角色名称搜索">
                        <i class="fa fa-search absolute left-3 top-1/2 -translate-y-1/2 text-neutral-400"></i>
                    </div>
                </div>
                <div>
                    <label for="data-scope-filter" class="block text-sm font-medium text-neutral-700 mb-1">数据范围</label>
                    <div class="relative">
                        <select id="data-scope-filter" class="form-input appearance-none">
                            <option value="">全部范围</option>
                            <option value="0">全部数据</option>
                            <option value="1">本机构及子机构数据</option>
                            <option value="2">本机构数据</option>
                            <option value="3">本人数据</option>
                            <option value="4">自定义数据</option>
                        </select>
                        <i class="fa fa-chevron-down absolute right-3 top-1/2 -translate-y-1/2 text-neutral-400 pointer-events-none"></i>
                    </div>
                </div>
                <div>
                    <label for="org-filter" class="block text-sm font-medium text-neutral-700 mb-1">所属机构</label>
                    <div class="relative">
                        <select id="org-filter" class="form-input appearance-none">
                            <option value="">全部机构</option>
                            <option value="1">总部</option>
                            <option value="2">技术部</option>
                            <option value="3">市场部</option>
                            <option value="4">财务部</option>
                        </select>
                        <i class="fa fa-chevron-down absolute right-3 top-1/2 -translate-y-1/2 text-neutral-400 pointer-events-none"></i>
                    </div>
                </div>
            </div>
            <div class="mt-4 flex justify-end space-x-3">
                <button id="reset-filter-btn" class="btn-secondary">
                    <i class="fa fa-refresh mr-1"></i> 重置
                </button>
                <button id="search-btn" class="btn-primary">
                    <i class="fa fa-search mr-1"></i> 搜索
                </button>
            </div>
        </div>

        <!-- 角色列表 -->
        <div class="bg-white rounded-xl shadow-sm card-shadow">
            <div class="overflow-x-auto">
                <table class="min-w-full divide-y divide-neutral-200">
                    <thead class="bg-neutral-50">
                    <tr>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-neutral-500 uppercase tracking-wider">角色名称</th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-neutral-500 uppercase tracking-wider">数据范围</th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-neutral-500 uppercase tracking-wider">所属机构</th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-neutral-500 uppercase tracking-wider">创建时间</th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-neutral-500 uppercase tracking-wider">状态</th>
                        <th scope="col" class="px-6 py-3 text-right text-xs font-medium text-neutral-500 uppercase tracking-wider">操作</th>
                    </tr>
                    </thead>
                    <tbody class="bg-white divide-y divide-neutral-200" id="roles-table-body">
                    <!-- 角色数据将通过JavaScript动态填充 -->
                    </tbody>
                </table>
            </div>
            <!-- 空状态显示 -->
            <div id="empty-state" class="hidden py-16 flex flex-col items-center justify-center">
                <div class="w-24 h-24 bg-neutral-100 rounded-full flex items-center justify-center mb-4">
                    <i class="fa fa-user-circle-o text-4xl text-neutral-300"></i>
                </div>
                <p class="text-neutral-500">暂无角色数据</p>
                <button id="empty-add-role-btn" class="mt-4 btn-primary">
                    <i class="fa fa-plus mr-1"></i> 新增角色
                </button>
            </div>
            <!-- 分页控件 -->
            <div class="px-6 py-3 bg-neutral-50 flex items-center justify-between border-t border-neutral-200" id="pagination-container">
                <div class="flex-1 flex justify-between sm:hidden">
                    <button id="prev-page-mobile" class="btn-secondary">上一页</button>
                    <button id="next-page-mobile" class="btn-secondary ml-3">下一页</button>
                </div>
                <div class="hidden sm:flex-1 sm:flex sm:items-center sm:justify-between">
                    <div>
                        <p class="text-sm text-neutral-600">
                            显示第 <span class="font-medium" id="current-page-text">1</span> 至 <span class="font-medium" id="end-page-text">10</span> 条，共 <span class="font-medium" id="total-records-text">24</span> 条记录
                        </p>
                    </div>
                    <div>
                        <nav class="relative z-0 inline-flex rounded-md shadow-sm -space-x-px" aria-label="Pagination">
                            <button id="prev-page" class="relative inline-flex items-center px-2 py-2 rounded-l-md border border-neutral-200 bg-white text-sm font-medium text-neutral-500 hover:bg-neutral-50">
                                <span class="sr-only">上一页</span>
                                <i class="fa fa-chevron-left text-xs"></i>
                            </button>
                            <button class="relative inline-flex items-center px-4 py-2 border border-neutral-200 bg-primary text-sm font-medium text-white">
                                1
                            </button>
                            <button class="relative inline-flex items-center px-4 py-2 border border-neutral-200 bg-white text-sm font-medium text-neutral-700 hover:bg-neutral-50">
                                2
                            </button>
                            <button class="relative inline-flex items-center px-4 py-2 border border-neutral-200 bg-white text-sm font-medium text-neutral-700 hover:bg-neutral-50">
                                3
                            </button>
                            <span class="relative inline-flex items-center px-4 py-2 border border-neutral-200 bg-white text-sm font-medium text-neutral-700">
                                    ...
                                </span>
                            <button class="relative inline-flex items-center px-4 py-2 border border-neutral-200 bg-white text-sm font-medium text-neutral-700 hover:bg-neutral-50">
                                5
                            </button>
                            <button id="next-page" class="relative inline-flex items-center px-2 py-2 rounded-r-md border border-neutral-200 bg-white text-sm font-medium text-neutral-500 hover:bg-neutral-50">
                                <span class="sr-only">下一页</span>
                                <i class="fa fa-chevron-right text-xs"></i>
                            </button>
                        </nav>
                    </div>
                </div>
            </div>
        </div>
    </div>
</main>

<!-- 新增/编辑角色的模态框 - 默认隐藏 -->
<div id="role-modal" class="fixed inset-0 bg-black/50 z-50 hidden items-center justify-center">
    <div class="bg-white rounded-xl w-full max-w-2xl max-h-[90vh] overflow-y-auto">
        <div class="p-5 border-b border-neutral-200 flex justify-between items-center">
            <h3 class="text-lg font-semibold text-neutral-800" id="role-modal-title">新增角色</h3>
            <button id="close-role-modal" class="text-neutral-500 hover:text-neutral-700">
                <i class="fa fa-times"></i>
            </button>
        </div>
        <div class="p-5">
            <form id="role-form">
                <input type="hidden" id="role-id">
                <div class="mb-4">
                    <label for="role-name" class="block text-sm font-medium text-neutral-700 mb-1">角色名称 <span class="text-danger">*</span></label>
                    <input type="text" id="role-name" class="form-input" placeholder="请输入角色名称">
                </div>

                <div class="mb-4">
                    <label for="role-remark" class="block text-sm font-medium text-neutral-700 mb-1">备注</label>
                    <textarea id="role-remark" rows="3" class="form-input" placeholder="请输入角色备注信息"></textarea>
                </div>

                <div class="mb-4">
                    <label for="data-scope" class="block text-sm font-medium text-neutral-700 mb-1">数据范围 <span class="text-danger">*</span></label>
                    <div class="relative">
                        <select id="data-scope" class="form-input appearance-none">
                            <option value="">请选择数据范围</option>
                            <option value="0">0：全部数据</option>
                            <option value="1">1：本机构及子机构数据</option>
                            <option value="2">2：本机构数据</option>
                            <option value="3">3：本人数据</option>
                            <option value="4">4：自定义数据</option>
                        </select>
                        <i class="fa fa-chevron-down absolute right-3 top-1/2 -translate-y-1/2 text-neutral-400 pointer-events-none"></i>
                    </div>
                </div>

                <div class="mb-4">
                    <label for="org-id" class="block text-sm font-medium text-neutral-700 mb-1">所属机构</label>
                    <div class="relative">
                        <select id="org-id" class="form-input appearance-none">
                            <option value="">请选择机构</option>
                            <option value="1">总部</option>
                            <option value="2">技术部</option>
                            <option value="3">市场部</option>
                            <option value="4">财务部</option>
                        </select>
                        <i class="fa fa-chevron-down absolute right-3 top-1/2 -translate-y-1/2 text-neutral-400 pointer-events-none"></i>
                    </div>
                </div>

                <div class="mb-4">
                    <label class="block text-sm font-medium text-neutral-700 mb-1">状态</label>
                    <div class="flex space-x-4">
                        <label class="inline-flex items-center">
                            <input type="radio" name="role-status" value="0" class="text-primary focus:ring-primary" checked>
                            <span class="ml-2 text-sm text-neutral-700">正常</span>
                        </label>
                        <label class="inline-flex items-center">
                            <input type="radio" name="role-status" value="1" class="text-primary focus:ring-primary">
                            <span class="ml-2 text-sm text-neutral-700">已删除</span>
                        </label>
                    </div>
                </div>

                <!-- 权限配置部分 -->
                <div class="mb-4 pt-4 border-t border-neutral-200">
                    <label class="block text-sm font-medium text-neutral-700 mb-3">权限配置</label>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <!-- 权限组1 -->
                        <div>
                            <div class="font-medium text-sm mb-2">用户管理</div>
                            <div class="space-y-2 pl-2">
                                <label class="inline-flex items-center">
                                    <input type="checkbox" class="rounded text-primary focus:ring-primary">
                                    <span class="ml-2 text-sm text-neutral-700">查看用户</span>
                                </label>
                                <label class="inline-flex items-center">
                                    <input type="checkbox" class="rounded text-primary focus:ring-primary">
                                    <span class="ml-2 text-sm text-neutral-700">新增用户</span>
                                </label>
                                <label class="inline-flex items-center">
                                    <input type="checkbox" class="rounded text-primary focus:ring-primary">
                                    <span class="ml-2 text-sm text-neutral-700">编辑用户</span>
                                </label>
                                <label class="inline-flex items-center">
                                    <input type="checkbox" class="rounded text-primary focus:ring-primary">
                                    <span class="ml-2 text-sm text-neutral-700">删除用户</span>
                                </label>
                            </div>
                        </div>
                        <!-- 权限组2 -->
                        <div>
                            <div class="font-medium text-sm mb-2">应用管理</div>
                            <div class="space-y-2 pl-2">
                                <label class="inline-flex items-center">
                                    <input type="checkbox" class="rounded text-primary focus:ring-primary">
                                    <span class="ml-2 text-sm text-neutral-700">查看应用</span>
                                </label>
                                <label class="inline-flex items-center">
                                    <input type="checkbox" class="rounded text-primary focus:ring-primary">
                                    <span class="ml-2 text-sm text-neutral-700">审核应用</span>
                                </label>
                                <label class="inline-flex items-center">
                                    <input type="checkbox" class="rounded text-primary focus:ring-primary">
                                    <span class="ml-2 text-sm text-neutral-700">下架应用</span>
                                </label>
                            </div>
                        </div>
                    </div>
                    <button type="button" class="mt-3 text-sm text-primary hover:underline">
                        <i class="fa fa-plus-circle mr-1"></i> 展开更多权限
                    </button>
                </div>
            </form>
        </div>
        <div class="p-5 border-t border-neutral-200 flex justify-end space-x-3">
            <button id="cancel-role-modal" class="btn-secondary">取消</button>
            <button id="save-role" class="btn-primary">保存</button>
        </div>
    </div>
</div>

<!-- 确认操作的模态框 - 默认隐藏 -->
<div id="confirm-modal" class="fixed inset-0 bg-black/50 z-50 hidden items-center justify-center">
    <div class="bg-white rounded-xl w-full max-w-md">
        <div class="p-5 border-b border-neutral-200">
            <h3 class="text-lg font-semibold text-neutral-800">确认操作</h3>
        </div>
        <div class="p-5">
            <p class="text-neutral-700" id="confirm-message">您确定要执行此操作吗？</p>
        </div>
        <div class="p-5 border-t border-neutral-200 flex justify-end space-x-3">
            <button id="cancel-confirm" class="btn-secondary">取消</button>
            <button id="confirm-action" class="btn-danger">确认</button>
        </div>
    </div>
</div>

<!-- 加载中提示 - 默认隐藏 -->
<div id="loading-overlay" class="fixed inset-0 bg-black/50 flex items-center justify-center z-50 hidden">
    <div class="bg-white p-6 rounded-lg shadow-xl flex items-center">
        <i class="fa fa-spinner fa-spin text-primary text-2xl mr-3"></i>
        <span>加载中，请稍候...</span>
    </div>
</div>

<!-- JavaScript 功能实现 -->
<script>
    // ==============================================
    // Token 管理工具类 - 与系统其他页面保持一致的认证机制
    // ==============================================

    const TokenManager = {
        // Token存储的键名
        TOKEN_KEY: 'zhizhu_app_store_token',
        // Token过期时间存储的键名
        EXPIRY_KEY: 'token_expiry',

        /**
         * 保存token到本地存储
         * @param {string} token - 后端返回的token字符串
         * @param {number} expiresIn - 有效期（秒），通常从后端获取
         */
        saveToken: function(token, expiresIn) {
            const expiryTime = new Date().getTime() + (expiresIn * 1000);
            localStorage.setItem(this.TOKEN_KEY, token);
            localStorage.setItem(this.EXPIRY_KEY, expiryTime.toString());
            console.log('Token已保存，有效期至:', new Date(expiryTime).toLocaleString());
        },

        /**
         * 从本地存储获取token
         * @returns {string|null} - 返回token或null
         */
        getToken: function() {
            if (!this.isTokenValid()) {
                this.removeToken();
                return null;
            }
            return localStorage.getItem(this.TOKEN_KEY);
        },

        /**
         * 检查token是否有效（存在且未过期）
         * @returns {boolean} - 是否有效
         */
        isTokenValid: function() {
            const token = localStorage.getItem(this.TOKEN_KEY);
            const expiryTime = localStorage.getItem(this.EXPIRY_KEY);

            if (!token) {
                return false;
            }

            const currentTime = new Date().getTime();
            return true;
        },

        /**
         * 从本地存储删除token
         */
        removeToken: function() {
            localStorage.removeItem(this.TOKEN_KEY);
            localStorage.removeItem(this.EXPIRY_KEY);
            console.log('Token已删除');
        }
    };

    // ==============================================
    // 认证相关函数
    // ==============================================

    /**
     * 检查用户是否已登录（token是否有效）
     * 如果未登录，跳转到登录页
     */
    function checkLoginStatus() {
        showLoading();

        if (!TokenManager.isTokenValid()) {
            console.log('未检测到有效登录状态，跳转到登录页');
            hideLoading();
            // 跳转到登录页，记录当前页面地址以便登录后返回
            window.location.href = `/login.html?redirect=${encodeURIComponent(window.location.href)}`;
            return false;
        }

        console.log('登录状态有效');
        return true;
    }

    /**
     * 处理退出登录
     */
    function handleLogout() {
        if (confirm('确定要退出登录吗？')) {
            showLoading();
            // 调用后端退出登录接口
            fetchLogout()
                .then(() => {
                    TokenManager.removeToken();
                    window.location.href = '/login.html';
                })
                .catch(error => {
                    console.error('退出登录失败:', error);
                    TokenManager.removeToken();
                    window.location.href = '/login.html';
                });
        }
    }

    // ==============================================
    // API调用工具函数 - 所有请求都会自动带上token
    // ==============================================

    /**
     * 带认证的API请求工具函数
     * 自动添加Authorization头，处理401错误
     * @param {string} url - 请求地址
     * @param {Object} options - fetch选项
     * @returns {Promise} - 返回Promise对象
     */
    function authenticatedFetch(url, options = {}) {
        const token = TokenManager.getToken();

        if (!token) {
            return Promise.reject(new Error('未登录或登录已过期'));
        }

        const headers = {
            'Content-Type': 'application/json',
            ...options.headers
        };

        headers['Authorization'] = `Bearer ${token}`;

        const fetchOptions = {
            ...options,
            headers
        };

        return fetch(url, fetchOptions)
            .then(response => {
                // 处理401未授权错误
                if (response.status === 401) {
                    TokenManager.removeToken();
                    window.location.href = `/login.html?redirect=${encodeURIComponent(window.location.href)}`;
                    return Promise.reject(new Error('登录已过期，请重新登录'));
                }

                if (!response.ok) {
                    return response.json()
                        .then(data => {
                            throw new Error(data.message || `请求失败: ${response.status}`);
                        })
                        .catch(() => {
                            throw new Error(`请求失败: ${response.status}`);
                        });
                }

                return response.json();
            });
    }

    // ==============================================
    // 后端接口调用 - 已集成token认证
    // 作为Java后端开发者，您需要关注这些接口地址和参数
    // ==============================================

    /**
     * 获取角色列表
     * @param {number} page - 页码
     * @param {number} pageSize - 每页数量
     * @param {Object} params - 查询参数
     */
    function fetchRoles(page = 1, pageSize = 10, params = {}) {
        console.log('获取角色列表，页码:', page, '参数:', params);

        // 构建查询参数
        const queryParams = new URLSearchParams({
            page: page,
            pageSize: pageSize,
            ...params
        });

        // 后端API地址 - 请替换为您的实际Java后端接口地址
        // 例如: /api/system/role/list
        const apiUrl = `/api/sys/roles?${queryParams.toString()}`;

        return authenticatedFetch(apiUrl);
    }

    /**
     * 获取角色详情
     * @param {string} roleId - 角色ID
     */
    function fetchRoleDetail(roleId) {
        console.log('获取角色详情，ID:', roleId);

        // 后端API地址 - 请替换为您的实际Java后端接口地址
        // 例如: /api/system/role/{id}
        const apiUrl = `/api/sys/roles/${roleId}`;

        return authenticatedFetch(apiUrl);
    }

    /**
     * 保存角色信息（新增或编辑）
     * @param {Object} roleData - 角色数据，对应sys_role表字段
     */
    function saveRole(roleData) {
        console.log('保存角色信息:', roleData);

        // 后端API地址 - 请替换为您的实际Java后端接口地址
        let apiUrl = '/api/sys/roles';  // 新增角色接口，例如: /api/system/role/save
        let method = 'POST';

        // 如果有ID，则是编辑操作
        if (roleData.id) {
            apiUrl = `/api/sys/roles/${roleData.id}`;  // 编辑角色接口，例如: /api/system/role/update
            method = 'PUT';
        }

        return authenticatedFetch(apiUrl, {
            method: method,
            body: JSON.stringify(roleData)
        });
    }

    /**
     * 删除角色
     * @param {string} roleId - 角色ID
     */
    function deleteRole(roleId) {
        console.log('删除角色，ID:', roleId);

        // 后端API地址 - 请替换为您的实际Java后端接口地址
        // 例如: /api/system/role/delete/{id}
        const apiUrl = `/api/sys/roles/${roleId}`;

        return authenticatedFetch(apiUrl, {
            method: 'DELETE'
        });
    }

    /**
     * 获取机构列表（用于下拉选择）
     */
    function fetchOrganizations() {
        console.log('获取机构列表');

        // 后端API地址 - 请替换为您的实际Java后端接口地址
        // 例如: /api/system/organization/list
        const apiUrl = '/api/sys/organizations';

        return authenticatedFetch(apiUrl);
    }

    /**
     * 获取权限列表（用于角色权限配置）
     */
    function fetchPermissions() {
        console.log('获取权限列表');

        // 后端API地址 - 请替换为您的实际Java后端接口地址
        // 例如: /api/system/permission/list
        const apiUrl = '/api/sys/permissions';

        return authenticatedFetch(apiUrl);
    }

    /**
     * 保存角色权限配置
     * @param {string} roleId - 角色ID
     * @param {Array} permissionIds - 权限ID数组
     */
    function saveRolePermissions(roleId, permissionIds) {
        console.log('保存角色权限，角色ID:', roleId, '权限IDs:', permissionIds);

        // 后端API地址 - 请替换为您的实际Java后端接口地址
        // 例如: /api/system/role/permission/save
        const apiUrl = `/api/sys/roles/${roleId}/permissions`;

        return authenticatedFetch(apiUrl, {
            method: 'POST',
            body: JSON.stringify({ permissionIds: permissionIds })
        });
    }

    /**
     * 获取当前管理员信息
     */
    function fetchAdminInfo() {
        console.log('获取管理员信息');

        // 后端API地址 - 请替换为您的实际Java后端接口地址
        const apiUrl = '/api/admin/current';

        return authenticatedFetch(apiUrl)
            .then(admin => {
                console.log('成功获取管理员信息:', admin);
                document.getElementById('admin-name').textContent = admin.name || '管理员';
                return admin;
            });
    }

    /**
     * 获取通知列表
     */
    function fetchNotifications() {
        console.log('获取通知列表');

        // 后端API地址 - 请替换为您的实际Java后端接口地址
        const apiUrl = '/api/admin/notifications';

        return authenticatedFetch(apiUrl)
            .then(notifications => {
                console.log('成功获取通知列表:', notifications);
                const unreadCount = notifications.filter(notification => !notification.read).length;
                document.getElementById('notification-count').textContent = unreadCount;
                return notifications;
            });
    }

    /**
     * 退出登录接口调用
     */
    function fetchLogout() {
        // 后端API地址 - 请替换为您的实际Java后端接口地址
        const apiUrl = '/api/admin/logout';

        return authenticatedFetch(apiUrl, {
            method: 'POST'
        });
    }

    // ==============================================
    // 页面初始化和事件绑定
    // ==============================================

    // 页面加载完成后执行初始化
    document.addEventListener('DOMContentLoaded', function() {
        // 检查登录状态，如果未登录会自动跳转
        if (!checkLoginStatus()) {
            return; // 如果未登录，不再执行后续初始化
        }

        // 初始化页面功能
        initPageFunctions();

        // 加载角色数据
        loadRolesData();
    });

    /**
     * 初始化页面功能
     */
    function initPageFunctions() {
        // 显示当前日期
        displayCurrentDate();

        // 初始化移动端菜单
        initMobileMenu();

        // 初始化用户菜单
        initUserMenu();

        // 初始化模态框功能
        initModals();

        // 初始化角色操作按钮
        initRoleActionButtons();

        // 初始化搜索和筛选功能
        initSearchAndFilter();

        // 初始化分页功能
        initPagination();
    }

    /**
     * 加载角色数据
     * @param {number} page - 页码，默认为1
     * @param {Object} params - 查询参数
     */
    function loadRolesData(page = 1, params = {}) {
        showLoading();

        // 并行加载角色数据和其他必要数据
        Promise.all([
            fetchRoles(page, 10, params),
            fetchOrganizations(),
            fetchPermissions(),
            fetchNotifications(),
            fetchAdminInfo()
        ])
            .then(results => {
                const rolesResponse = results[0];
                console.log('角色数据加载完成:', rolesResponse);

                // 更新角色列表UI
                renderRolesTable(rolesResponse.records);

                // 更新分页信息
                updatePagination(
                    page,
                    rolesResponse.pageSize,
                    rolesResponse.total,
                    rolesResponse.pages
                );

                // 更新总角色数
                document.getElementById('total-roles').textContent = rolesResponse.total;
                document.getElementById('total-records-text').textContent = rolesResponse.total;
            })
            .catch(error => {
                console.error('角色数据加载失败:', error);
                showErrorNotification('数据加载失败，请刷新页面重试');
                // 显示空状态
                document.getElementById('roles-table-body').innerHTML = '';
                document.getElementById('empty-state').classList.remove('hidden');
                document.getElementById('pagination-container').classList.add('hidden');
            })
            .finally(() => {
                hideLoading();
            });
    }

    // ==============================================
    // 页面功能实现
    // ==============================================

    /**
     * 显示当前日期
     */
    function displayCurrentDate() {
        const now = new Date();
        const options = {
            year: 'numeric',
            month: 'long',
            day: 'numeric',
            weekday: 'long'
        };
        const formattedDate = now.toLocaleDateString('zh-CN', options);
        document.getElementById('current-date').textContent = formattedDate;
    }

    /**
     * 初始化移动端菜单
     */
    function initMobileMenu() {
        const mobileMenuButton = document.getElementById('mobile-menu-button');
        const sidebar = document.getElementById('sidebar');

        mobileMenuButton.addEventListener('click', function() {
            sidebar.classList.toggle('hidden');
            sidebar.classList.toggle('fixed');
            sidebar.classList.toggle('inset-0');
            sidebar.classList.toggle('z-40');
        });

        // 点击外部关闭侧边栏
        document.addEventListener('click', function(event) {
            if (window.innerWidth < 768 &&
                !sidebar.classList.contains('hidden') &&
                !sidebar.contains(event.target) &&
                event.target !== mobileMenuButton) {
                sidebar.classList.add('hidden');
                sidebar.classList.remove('fixed', 'inset-0', 'z-40');
            }
        });
    }

    /**
     * 初始化用户菜单
     */
    function initUserMenu() {
        const userMenuButton = document.getElementById('user-menu-button');
        const userDropdownMenu = document.getElementById('user-dropdown-menu');
        const logoutButton = document.getElementById('logout-button');

        // 切换用户菜单显示/隐藏
        userMenuButton.addEventListener('click', function(e) {
            e.stopPropagation();
            userDropdownMenu.classList.toggle('hidden');
        });

        // 点击外部关闭用户菜单
        document.addEventListener('click', function() {
            userDropdownMenu.classList.add('hidden');
        });

        // 阻止菜单内部点击事件冒泡
        userDropdownMenu.addEventListener('click', function(e) {
            e.stopPropagation();
        });

        // 绑定退出登录事件
        logoutButton.addEventListener('click', handleLogout);
    }

    /**
     * 初始化模态框功能
     */
    function initModals() {
        const roleModal = document.getElementById('role-modal');
        const closeRoleModal = document.getElementById('close-role-modal');
        const cancelRoleModal = document.getElementById('cancel-role-modal');
        const saveRoleBtn = document.getElementById('save-role');
        const confirmModal = document.getElementById('confirm-modal');
        const cancelConfirm = document.getElementById('cancel-confirm');
        const confirmAction = document.getElementById('confirm-action');
        const addRoleBtn = document.getElementById('add-role-btn');
        const emptyAddRoleBtn = document.getElementById('empty-add-role-btn');

        // 关闭角色模态框
        function closeModal() {
            roleModal.classList.add('hidden');
            roleModal.classList.remove('flex');
            confirmModal.classList.add('hidden');
            confirmModal.classList.remove('flex');
        }

        closeRoleModal.addEventListener('click', closeModal);
        cancelRoleModal.addEventListener('click', closeModal);
        cancelConfirm.addEventListener('click', closeModal);

        // 点击模态框外部关闭
        roleModal.addEventListener('click', function(e) {
            if (e.target === roleModal) {
                closeModal();
            }
        });

        confirmModal.addEventListener('click', function(e) {
            if (e.target === confirmModal) {
                closeModal();
            }
        });

        // 保存角色信息
        saveRoleBtn.addEventListener('click', function() {
            saveRoleFormData();
        });

        // 确认操作
        confirmAction.addEventListener('click', function() {
            executeConfirmedAction();
        });

        // 新增角色按钮
        addRoleBtn.addEventListener('click', function() {
            openEditRoleModal();
        });

        // 空状态下的新增角色按钮
        emptyAddRoleBtn.addEventListener('click', function() {
            openEditRoleModal();
        });
    }

    /**
     * 初始化角色操作按钮
     */
    function initRoleActionButtons() {
        // 这里的按钮是动态生成的，所以需要使用事件委托
        document.getElementById('roles-table-body').addEventListener('click', function(e) {
            // 编辑角色按钮
            if (e.target.closest('.role-edit-btn')) {
                const btn = e.target.closest('.role-edit-btn');
                const roleId = btn.getAttribute('data-role-id');
                openEditRoleModal(roleId);
            }

            // 删除角色按钮
            if (e.target.closest('.role-delete-btn')) {
                const btn = e.target.closest('.role-delete-btn');
                const roleId = btn.getAttribute('data-role-id');
                const roleName = btn.getAttribute('data-role-name');

                openConfirmModal(
                    `您确定要删除角色"${roleName}"吗？删除后相关用户将失去该角色权限。`,
                    'delete',
                    roleId
                );
            }

            // 权限配置按钮
            if (e.target.closest('.role-permission-btn')) {
                const btn = e.target.closest('.role-permission-btn');
                const roleId = btn.getAttribute('data-role-id');
                const roleName = btn.getAttribute('data-role-name');

                // 打开权限配置模态框
                openEditRoleModal(roleId);
                // 这里可以滚动到权限配置部分
            }
        });
    }

    /**
     * 初始化搜索和筛选功能
     */
    function initSearchAndFilter() {
        const searchBtn = document.getElementById('search-btn');
        const resetFilterBtn = document.getElementById('reset-filter-btn');

        // 搜索按钮点击事件
        searchBtn.addEventListener('click', function() {
            // 获取搜索参数
            const params = {
                name: document.getElementById('role-name-search').value.trim(),
                dataScope: document.getElementById('data-scope-filter').value,
                orgId: document.getElementById('org-filter').value
            };

            // 加载第一页数据
            loadRolesData(1, params);
        });

        // 重置按钮点击事件
        resetFilterBtn.addEventListener('click', function() {
            // 重置表单
            document.getElementById('role-name-search').value = '';
            document.getElementById('data-scope-filter').value = '';
            document.getElementById('org-filter').value = '';

            // 加载第一页数据
            loadRolesData(1, {});
        });

        // 按回车键触发搜索
        document.getElementById('role-name-search').addEventListener('keyup', function(e) {
            if (e.key === 'Enter') {
                searchBtn.click();
            }
        });
    }

    /**
     * 初始化分页功能
     */
    function initPagination() {
        const prevPageBtn = document.getElementById('prev-page');
        const nextPageBtn = document.getElementById('next-page');
        const prevPageMobileBtn = document.getElementById('prev-page-mobile');
        const nextPageMobileBtn = document.getElementById('next-page-mobile');

        // 上一页按钮点击事件
        prevPageBtn.addEventListener('click', function() {
            const currentPage = parseInt(document.getElementById('current-page-text').textContent);
            if (currentPage > 1) {
                loadCurrentSearchParams(currentPage - 1);
            }
        });

        // 下一页按钮点击事件
        nextPageBtn.addEventListener('click', function() {
            const currentPage = parseInt(document.getElementById('current-page-text').textContent);
            const totalPages = Math.ceil(parseInt(document.getElementById('total-records-text').textContent) / 10);
            if (currentPage < totalPages) {
                loadCurrentSearchParams(currentPage + 1);
            }
        });

        // 移动端上一页按钮
        prevPageMobileBtn.addEventListener('click', function() {
            prevPageBtn.click();
        });

        // 移动端下一页按钮
        nextPageMobileBtn.addEventListener('click', function() {
            nextPageBtn.click();
        });
    }

    /**
     * 根据当前搜索条件加载指定页数据
     * @param {number} page - 页码
     */
    function loadCurrentSearchParams(page) {
        const params = {
            name: document.getElementById('role-name-search').value.trim(),
            dataScope: document.getElementById('data-scope-filter').value,
            orgId: document.getElementById('org-filter').value
        };

        loadRolesData(page, params);
    }

    // ==============================================
    // 页面渲染函数
    // ==============================================

    /**
     * 渲染角色列表表格
     * @param {Array} roles - 角色数组
     */
    function renderRolesTable(roles) {
        const tableBody = document.getElementById('roles-table-body');
        tableBody.innerHTML = '';

        // 如果没有数据，显示空状态
        if (!roles || roles.length === 0) {
            document.getElementById('empty-state').classList.remove('hidden');
            document.getElementById('pagination-container').classList.add('hidden');
            return;
        }

        // 隐藏空状态，显示分页
        document.getElementById('empty-state').classList.add('hidden');
        document.getElementById('pagination-container').classList.remove('hidden');

        // 遍历角色数据，生成表格行
        roles.forEach(role => {
            const row = document.createElement('tr');

            // 格式化数据范围显示文本
            const dataScopeText = getDataSourceText(role.dataScope);

            // 格式化状态显示
            const statusClass = role.deleted === 0 ? 'bg-success/10 text-success' : 'bg-neutral-100 text-neutral-500';
            const statusText = role.deleted === 0 ? '正常' : '已删除';

            // 格式化日期
            const createTime = role.createTime ? new Date(role.createTime).toLocaleString() : '';

            // 设置行内容
            row.innerHTML = `
                    <td class="px-6 py-4 whitespace-nowrap">
                        <div class="text-sm font-medium text-neutral-800">${role.name}</div>
                        <div class="text-xs text-neutral-500">${role.remark || '-'}</div>
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap">
                        <div class="text-sm text-neutral-600">${dataScopeText}</div>
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap">
                        <div class="text-sm text-neutral-600">${getOrgName(role.orgId)}</div>
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-neutral-600">
                        ${createTime}
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap">
                        <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${statusClass}">${statusText}</span>
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                        <button class="text-primary hover:text-primary/80 mr-3 role-permission-btn"
                                data-role-id="${role.id}"
                                data-role-name="${role.name}">权限</button>
                        <button class="text-neutral-600 hover:text-neutral-900 mr-3 role-edit-btn"
                                data-role-id="${role.id}">编辑</button>
                        <button class="text-danger hover:text-danger/80 role-delete-btn"
                                data-role-id="${role.id}"
                                data-role-name="${role.name}">删除</button>
                    </td>
                `;

            tableBody.appendChild(row);
        });
    }

    /**
     * 更新分页信息
     * @param {number} currentPage - 当前页码
     * @param {number} pageSize - 每页数量
     * @param {number} total - 总记录数
     * @param {number} totalPages - 总页数
     */
    function updatePagination(currentPage, pageSize, total, totalPages) {
        document.getElementById('current-page-text').textContent = currentPage;

        const endRecord = Math.min(currentPage * pageSize, total);
        document.getElementById('end-page-text').textContent = endRecord;

        // 禁用/启用分页按钮
        const prevPageBtn = document.getElementById('prev-page');
        const nextPageBtn = document.getElementById('next-page');

        if (currentPage === 1) {
            prevPageBtn.classList.add('opacity-50', 'cursor-not-allowed');
            prevPageBtn.disabled = true;
        } else {
            prevPageBtn.classList.remove('opacity-50', 'cursor-not-allowed');
            prevPageBtn.disabled = false;
        }

        if (currentPage >= totalPages) {
            nextPageBtn.classList.add('opacity-50', 'cursor-not-allowed');
            nextPageBtn.disabled = true;
        } else {
            nextPageBtn.classList.remove('opacity-50', 'cursor-not-allowed');
            nextPageBtn.disabled = false;
        }
    }

    // ==============================================
    // 模态框操作函数
    // ==============================================

    /**
     * 打开编辑角色模态框
     * @param {string} roleId - 角色ID，为空则是新增
     */
    function openEditRoleModal(roleId) {
        const roleModal = document.getElementById('role-modal');
        const modalTitle = document.getElementById('role-modal-title');
        const roleIdInput = document.getElementById('role-id');

        // 重置表单
        document.getElementById('role-form').reset();

        if (roleId) {
            // 编辑已有角色
            modalTitle.textContent = '编辑角色';
            roleIdInput.value = roleId;

            showLoading();
            // 获取角色详情并填充表单
            fetchRoleDetail(roleId)
                .then(role => {
                    // 填充表单数据 - 对应sys_role表字段
                    document.getElementById('role-name').value = role.name || '';
                    document.getElementById('role-remark').value = role.remark || '';
                    document.getElementById('data-scope').value = role.dataScope !== undefined ? role.dataScope.toString() : '';
                    document.getElementById('org-id').value = role.orgId || '';

                    // 设置状态单选按钮
                    const statusRadios = document.querySelectorAll('input[name="role-status"]');
                    statusRadios.forEach(radio => {
                        // deleted字段 0:正常 1:已删除
                        if (radio.value === (role.deleted || 0).toString()) {
                            radio.checked = true;
                        }
                    });

                    // TODO: 加载角色权限并选中对应的复选框

                    // 显示模态框
                    roleModal.classList.remove('hidden');
                    roleModal.classList.add('flex');
                })
                .catch(error => {
                    console.error('获取角色详情失败:', error);
                    showErrorNotification('加载角色详情失败');
                })
                .finally(() => {
                    hideLoading();
                });
        } else {
            // 新增角色
            modalTitle.textContent = '新增角色';
            roleIdInput.value = '';
            roleModal.classList.remove('hidden');
            roleModal.classList.add('flex');
        }
    }

    /**
     * 打开确认操作模态框
     * @param {string} message - 确认消息
     * @param {string} type - 操作类型：'delete' 等
     * @param {string} id - 操作对象ID
     */
    function openConfirmModal(message, type, id) {
        const confirmModal = document.getElementById('confirm-modal');
        const confirmMessage = document.getElementById('confirm-message');

        // 设置确认消息
        confirmMessage.textContent = message;

        // 存储要操作的对象信息
        confirmModal.setAttribute('data-type', type);
        confirmModal.setAttribute('data-id', id);

        // 显示模态框
        confirmModal.classList.remove('hidden');
        confirmModal.classList.add('flex');
    }

    /**
     * 执行确认的操作
     */
    function executeConfirmedAction() {
        const confirmModal = document.getElementById('confirm-modal');
        const type = confirmModal.getAttribute('data-type');
        const id = confirmModal.getAttribute('data-id');

        showLoading();

        if (type === 'delete') {
            // 处理角色删除
            deleteRole(id)
                .then(result => {
                    console.log('角色删除成功:', result);
                    showSuccessNotification('角色删除成功');

                    // 重新加载当前页数据
                    const currentPage = parseInt(document.getElementById('current-page-text').textContent);
                    loadCurrentSearchParams(currentPage);
                })
                .catch(error => {
                    console.error('角色删除失败:', error);
                    showErrorNotification('删除失败，请重试');
                })
                .finally(() => {
                    hideLoading();
                    confirmModal.classList.add('hidden');
                    confirmModal.classList.remove('flex');
                });
        }
    }

    /**
     * 保存角色表单数据
     */
    function saveRoleFormData() {
        // 收集表单数据 - 对应sys_role表字段
        const roleData = {
            id: document.getElementById('role-id').value || null,
            name: document.getElementById('role-name').value.trim(),
            remark: document.getElementById('role-remark').value.trim(),
            dataScope: document.getElementById('data-scope').value ? parseInt(document.getElementById('data-scope').value) : null,
            orgId: document.getElementById('org-id').value ? parseInt(document.getElementById('org-id').value) : null,
            deleted: document.querySelector('input[name="role-status"]:checked').value ? parseInt(document.querySelector('input[name="role-status"]:checked').value) : 0
            // creator, createTime, updater, updateTime 通常由后端自动处理
            // version 用于乐观锁，由后端处理
        };

        // 简单验证
        if (!roleData.name) {
            showErrorNotification('请输入角色名称');
            return;
        }

        if (roleData.dataScope === null) {
            showErrorNotification('请选择数据范围');
            return;
        }

        showLoading();

        // 保存角色数据
        saveRole(roleData)
            .then(result => {
                console.log('角色保存成功:', result);
                showSuccessNotification(roleData.id ? '角色更新成功' : '角色添加成功');

                // 关闭模态框并重新加载当前页数据
                const roleModal = document.getElementById('role-modal');
                roleModal.classList.add('hidden');
                roleModal.classList.remove('flex');

                const currentPage = roleData.id ?
                    parseInt(document.getElementById('current-page-text').textContent) : 1;
                loadCurrentSearchParams(currentPage);
            })
            .catch(error => {
                console.error('角色保存失败:', error);
                showErrorNotification('保存失败，请重试');
            })
            .finally(() => {
                hideLoading();
            });
    }

    // ==============================================
    // 工具函数
    // ==============================================

    /**
     * 根据数据范围值获取显示文本
     * @param {number} dataScope - 数据范围值
     * @returns {string} 显示文本
     */
    function getDataSourceText(dataScope) {
        const dataScopeMap = {
            0: '全部数据',
            1: '本机构及子机构数据',
            2: '本机构数据',
            3: '本人数据',
            4: '自定义数据'
        };
        return dataScopeMap[dataScope] || `未知(${dataScope})`;
    }

    /**
     * 根据机构ID获取机构名称
     * @param {number} orgId - 机构ID
     * @returns {string} 机构名称
     */
    function getOrgName(orgId) {
        // 实际应用中应该从后端获取的机构列表中查找
        const orgMap = {
            1: '总部',
            2: '技术部',
            3: '市场部',
            4: '财务部'
        };
        return orgMap[orgId] || `未知(${orgId})`;
    }

    /**
     * 显示加载状态
     */
    function showLoading() {
        document.getElementById('loading-overlay').classList.remove('hidden');
    }

    /**
     * 隐藏加载状态
     */
    function hideLoading() {
        document.getElementById('loading-overlay').classList.add('hidden');
    }

    /**
     * 显示错误通知
     * @param {string} message - 错误信息
     */
    function showErrorNotification(message) {
        alert(`错误: ${message}`);
    }

    /**
     * 显示成功通知
     * @param {string} message - 成功信息
     */
    function showSuccessNotification(message) {
        alert(`成功: ${message}`);
    }
</script>
</body>
</html>
